package com.cat.dataStructure02;

/**
 *   @description https://leetcode.cn/problems/evaluate-reverse-polish-notation/
 *   @author 曲大人的喵
 *   @create 2025/10/26 18:47
 *   @since JDK17
 */

public class Solution64 {
    boolean check(String x) {
        return x.equals("+") || x.equals("-") || x.equals("*") || x.equals("/");
    }

    public int evalRPN(String[] tokens) {
        int n = tokens.length, top = 0;
        int[] stack = new int[n];
        for (int i = 0; i < n; i++) {
            String x = tokens[i];
            if (!check(x)) { // 非运算符
                stack[top++] = Integer.valueOf(tokens[i]);
            } else {
                int n1 = stack[top - 2], n2 = stack[top - 1], t;
                if (x.equals("+")) {
                    t = n1 + n2;
                } else if (x.equals("-")) {
                    t = n1 - n2;
                } else if (x.equals("*")) {
                    t = n1 * n2;
                } else {
                    t = n1 / n2;
                }
                top -= 2;
                stack[top++] = t;
            }
        }

        return stack[0];
    }
}
